/*
 * Copyright 2022 The Open Islands Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.openislands.oi.console.config.completer;

import org.jline.reader.Candidate;
import org.jline.reader.LineReader;
import org.jline.reader.ParsedLine;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class SingleParamsCompleter extends ParamsCompleter {

    public SingleParamsCompleter(Map<String, List<Candidate>> commandParamsCandidates) {
        super(commandParamsCandidates);
    }

    @Override
    public void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) {
        List<String> words = line.words();
        String readLine = reader.getBuffer().toString();
        if (words.size() < 2) {
            words = Arrays.stream(readLine.split(" ")).filter(s -> !s.isEmpty()).collect(Collectors.toList());
        }

        // command match
        String key = words.get(0);
        List<Candidate> candidateList = super.commandParamsCandidates.get(key);
        if (Objects.nonNull(candidateList)) {

            // if, get candidates. else, matches all previous keys
            if (readLine.equals(line.line())) {
                // fill candidate
                super.valueCandidate(line, candidates);

                // prev key not param name
                String prevKey = words.get(words.size() - 2);
                if (!super.valueCache.get(key).contains(prevKey)) {
                    // filter entered parameter
                    Set<String> filter = new HashSet<>(words);
                    Stream<Candidate> candidateStream = candidateList.stream()
                            .filter(candidate -> !filter.contains(candidate.value()));
                    candidates.addAll(candidateStream.collect(Collectors.toList()));
                }
            } else {
                candidates.addAll(words.stream().map(Candidate::new).collect(Collectors.toSet()));
            }
        }
    }
}
